package com.ruoyi.web.controller.audit;

/*
 *  @author 雨安
 *  类名： AuditController
 *  创建时间：2025/2/21
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.enumutil.*;
import com.ruoyi.system.mapper.InviteMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.VipReleaseUserIdMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.web.config.TencentCosConfig;
import com.ruoyi.web.config.WxPayConfig;
import com.ruoyi.web.mapper.OrderInfoMapper;
import com.ruoyi.web.pojo.OrderInfo;
import com.ruoyi.web.uniEnum.OrderInfoEnum;
import org.apache.commons.math3.analysis.function.Add;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

@RestController
@RequestMapping("/user/audit")
public class AuditController {

    //审核表
    @Resource
    private AuditRecordsService auditRecordsService;
    //用户
    @Resource
    private SysUserMapper sysUserMapper;
    //添加任务
    @Resource
    private AddWechatService addWechatService;
    //订单
    @Resource
    private OrderInfoMapper orderInfoMapper;
    //上下级
    @Resource
    private InviteService inviteService;
    //冻结表
    @Resource
    private FreezeService freezeService;
    //群聊
    @Resource
    private AddGroupService addGroupService;
    //广场
    @Resource
    private PlazaService plazaService;


    //修改个人名片
    @PostMapping("/get/updateMybusinesscard")
    public AjaxResult updateMybusinesscard(@RequestBody AddWechat addWechat){
        if (addWechat.getNeedCount() <= 0){
            //返回结果
            return AjaxResult.error("人数填写有误,请重新填写。");
        }
        //获取原来的add对象
        AddWechat yAdd = addWechatService.getOne(new LambdaQueryWrapper<AddWechat>()
                .eq(AddWechat::getId, addWechat.getId())
        );
        if (yAdd.getNeedCount() == addWechat.getNeedCount()){
            //进入此处直接修改
            System.out.println("进入了此处哈哈啊啊啊啊啊啊");
            //设置默认值
            addWechat.setUpdateTime(new Date());
            addWechat.setDeleteFlag(Boolean.FALSE);
            //调用Service层删除
            addWechatService.updateById(addWechat);
            //返回结果
            return AjaxResult.success("修改成功");
        }else{
            //进入此处代表需求人数发声变化

            //判断人数是否不相等
            if (yAdd.getNeedCount() > addWechat.getNeedCount()){
                System.out.println("进入此处需要给用户反钱" + yAdd.getNeedCount() + "asklfdjasklfjaslkfa" + addWechat.getNeedCount());
                //获得需要退款人数的数量
                Integer resultCount = yAdd.getNeedCount() - addWechat.getNeedCount();
                //获取退款金额
                Double  resultFund = resultCount * 1.5;
                //修改冻结表
                freezeService.update(null,new UpdateWrapper<Freeze>().lambda()
                        //冻结任务编号
                        .eq(Freeze::getAddId,addWechat.getId())
                        //设置冻结金额
//                        .set(Freeze::getFreezeFund,resultFund)
                        .set(Freeze::getFreezeFund,addWechat.getNeedCount() * 1.5)
                );
                //修改个人余额积分
                SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
                //设置用户余额积分
                sysUser.setScore(sysUser.getScore().add(BigDecimal.valueOf(resultFund)));
                //设置默认值
                sysUser.setUpdateTime(new Date());
                sysUser.setUpdateBy(SecurityUtils.getUsername());
                //执行修改
                sysUserMapper.updateUser(sysUser);
                //创建订单对象
                OrderInfo orderInfo = new OrderInfo();
                //设置订单号
                orderInfo.setOrderNo("用户修改个人名片,人数变少退回部分积分,无订单号");
                //设置金额
                orderInfo.setFund(BigDecimal.valueOf(resultFund));
                //设置用户编号
                orderInfo.setUserId(SecurityUtils.getUserId());
                //设置订单备注
                orderInfo.setDescription("好友任务需求人数减少,退回部分积分。");
                //设置订单状态
                orderInfo.setOrderType(OrderInfoEnum.MingPianTuiKuan.getType());
                //设置默认值
                orderInfo.setCreateTime(new Date());
                orderInfo.setCreateBy(SecurityUtils.getUsername());
                orderInfo.setUpdateTime(new Date());
                orderInfo.setUpdateBy(SecurityUtils.getUsername());
                orderInfo.setDeleteFlag(Boolean.FALSE);
                //执行添加
                orderInfoMapper.insert(orderInfo);
            }else if (yAdd.getNeedCount() < addWechat.getNeedCount()){
                System.out.println("进入此处需要给用户扣钱");
                //获取需要增加的人数
                Integer resultCount = addWechat.getNeedCount() - yAdd.getNeedCount();
                //获取需要冻结的金额
                Double  resultFund = resultCount * 1.5;
                //查询个人余额积分
                SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
                //判断是否有足够多的积分
                if (sysUser.getScore().compareTo(BigDecimal.valueOf(resultFund)) >= 0) {
                    //设置用户余额积分
                    sysUser.setScore(sysUser.getScore().subtract(BigDecimal.valueOf(resultFund)));
                    // 获取当前冻结记录
                    Freeze currentFreeze = freezeService.getOne(new LambdaQueryWrapper<Freeze>()
                            .eq(Freeze::getAddId, addWechat.getId())
                    );
                    // 检查当前冻结记录是否存在
                    if (currentFreeze != null) {
                        System.out.println(currentFreeze.getFreezeFund() + "我是给用户扣钱查看" + resultCount + "========" + resultFund);
                        // 获取当前冻结金额
                        BigDecimal freezeFund = currentFreeze.getFreezeFund();
                        // 计算新的冻结金额
                        BigDecimal add = freezeFund.add(BigDecimal.valueOf(resultFund));
                        //修改冻结表
                        freezeService.update(null, new UpdateWrapper<Freeze>().lambda()
                                //冻结任务编号
                                .eq(Freeze::getAddId, addWechat.getId())
                                //设置冻结金额
                                .set(Freeze::getFreezeFund, add)
                        );
                    }
                    //设置默认值
                    sysUser.setUpdateTime(new Date());
                    sysUser.setUpdateBy(SecurityUtils.getUsername());
                    //执行修改
                    sysUserMapper.updateUser(sysUser);
                    //创建订单对象
                    OrderInfo orderInfo = new OrderInfo();
                    //设置订单号
                    orderInfo.setOrderNo("用户修改个人名片,人数增加扣款金额,无订单号");
                    //设置金额
                    orderInfo.setFund(BigDecimal.valueOf(resultFund).negate());
                    //设置用户编号
                    orderInfo.setUserId(SecurityUtils.getUserId());
                    //设置订单备注
                    orderInfo.setDescription("好友任务需求人数增加,扣除部分积分。");
                    //设置订单状态
                    orderInfo.setOrderType(OrderInfoEnum.MingPianKouKuan.getType());
                    //设置默认值
                    orderInfo.setCreateTime(new Date());
                    orderInfo.setCreateBy(SecurityUtils.getUsername());
                    orderInfo.setUpdateTime(new Date());
                    orderInfo.setUpdateBy(SecurityUtils.getUsername());
                    orderInfo.setDeleteFlag(Boolean.FALSE);
                    //执行添加
                    orderInfoMapper.insert(orderInfo);
                }else{
                    return AjaxResult.error("用户积分不足,请充值积分后进行修改。");
                }
            }
        }
        //设置默认值
        addWechat.setUpdateTime(new Date());
        addWechat.setDeleteFlag(Boolean.FALSE);
        //调用Service层删除
        addWechatService.updateById(addWechat);
        //返回结果
        return AjaxResult.success("修改成功");
    }


    //用户广场置顶
    @PostMapping("/top/plaza/{id}")
    public AjaxResult topPlaza(@PathVariable(value = "id")Long id){
        //查询广场
        Plaza plaza = plazaService.getOne(new LambdaQueryWrapper<Plaza>()
                //主键id
                .eq(Plaza::getId,id)
                //状态
                .eq(Plaza::getStatus, PlazaEnum.ShenHeTongGuo.getStatus())
                //逻辑删除
                .eq(Plaza::getDeleteFlag,Boolean.FALSE)
        );
        //判断广场不为 null
        if (Objects.nonNull(plaza)){
            //查询登录用户
            SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
            //相减判断用户是否余额足够
            BigDecimal subtract = sysUser.getScore().subtract(BigDecimal.valueOf(5L));
            //判断是否足够
            if (subtract.compareTo(BigDecimal.ZERO) > 0) {
                //设置余额
                sysUser.setScore(subtract);
                //设置默认值
                sysUser.setUpdateTime(new Date());
                sysUser.setUpdateBy(SecurityUtils.getUsername());
                //执行修改
                sysUserMapper.updateUser(sysUser);
                //将广场热度增加 1w
                int randomNumber = (int)(Math.random() * 10000) + 1; // 生成 1 到 10000 的随机整数
                //随机添加热度
                plaza.setHeat(plaza.getHeat() + randomNumber);
                //设置默认值
                plaza.setUpdateBy(SecurityUtils.getUsername());
                plaza.setUpdateTime(new Date());
                //设置置顶时间
                plaza.setTopTime(new Date());
                //执行修改
                plazaService.updateById(plaza);
                //添加置顶消费记录
                //创建订单对象
                OrderInfo orderInfo = new OrderInfo();
                //设置订单号
                orderInfo.setOrderNo("置顶消费-无订单。");
                //设置金额
                orderInfo.setFund(BigDecimal.valueOf(5).negate());
                //设置用户编号
                orderInfo.setUserId(SecurityUtils.getUserId());
                //设置订单备注
                orderInfo.setDescription("广场置顶消耗");
                //设置订单状态
                orderInfo.setOrderType(OrderInfoEnum.ZhiDingXiaoFei.getType());
                //设置默认值
                orderInfo.setCreateTime(new Date());
                orderInfo.setCreateBy(SecurityUtils.getUsername());
                orderInfo.setUpdateTime(new Date());
                orderInfo.setUpdateBy(SecurityUtils.getUsername());
                orderInfo.setDeleteFlag(Boolean.FALSE);
                //执行添加
                orderInfoMapper.insert(orderInfo);
                //返回结果
                return AjaxResult.success("置顶成功");
            }else{
                //返回结果
                return AjaxResult.success("用户余额不足");
            }
        }else{
            //返回结果
            return AjaxResult.success("广场异常");
        }
    }

    //置顶微信群
    @PostMapping("/top/group/{id}")
    public AjaxResult topGroup(@PathVariable(value = "id")Long id){
        //查询登录用户
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //相减判断用户是否余额足够
        BigDecimal subtract = sysUser.getScore().subtract(BigDecimal.valueOf(5L));
        //判断是否足够
        if (subtract.compareTo(BigDecimal.ZERO) < 0) {
            //返回结果
            return AjaxResult.success("用户余额不足,请充值积分。");
        }
        //扣除用户余额
        sysUser.setScore(subtract);
        //设置默认值
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        sysUser.setUpdateTime(new Date());
        //执行修改
        sysUserMapper.updateUser(sysUser);
        //创建订单对象
        OrderInfo orderInfo = new OrderInfo();
        //设置订单号
        orderInfo.setOrderNo("置顶消费-无订单。");
        //设置金额
        orderInfo.setFund(BigDecimal.valueOf(5).negate());
        //设置用户编号
        orderInfo.setUserId(SecurityUtils.getUserId());
        //设置订单备注
        orderInfo.setDescription("群聊置顶消耗");
        //设置订单状态
        orderInfo.setOrderType(OrderInfoEnum.ZhiDingXiaoFei.getType());
        //设置默认值
        orderInfo.setCreateTime(new Date());
        orderInfo.setCreateBy(SecurityUtils.getUsername());
        orderInfo.setUpdateTime(new Date());
        orderInfo.setUpdateBy(SecurityUtils.getUsername());
        orderInfo.setDeleteFlag(Boolean.FALSE);
        //执行添加
        orderInfoMapper.insert(orderInfo);
        //查询group
        AddGroup addGroup = addGroupService.getOne(new LambdaQueryWrapper<AddGroup>()
                //主键
                .eq(AddGroup::getId,id)
                //状态
                .eq(AddGroup::getStatus, AddGroupEnum.ShenHeTongGuo.getStatus())
                //逻辑删除
                .eq(AddGroup::getDeleteFlag,Boolean.FALSE)
        );
        //判断group不为 null
        if (Objects.nonNull(addGroup)) {
            if (Objects.nonNull(addGroup.getTopEndTime()) && addGroup.getTopEndTime().after(new Date())){
                //再原基础上加一小时
                Calendar calendar = Calendar.getInstance();
                //设置日期为当前置顶结束时间
                calendar.setTime(addGroup.getTopEndTime());
                // 加一小时
                calendar.add(Calendar.HOUR, 1);
                //得到日期
                Date newTopEndTime = calendar.getTime();
                //设置结束时间
                addGroup.setTopEndTime(newTopEndTime);
                //设置置顶时间
                addGroup.setTopTime(new Date());
                //执行修改
                addGroupService.updateById(addGroup);
            }else{
                //置顶一小时
                Calendar calendar = Calendar.getInstance();
                // 当前时间
                calendar.setTime(new Date());
                // 加一小时
                calendar.add(Calendar.HOUR, 1);
                //得到置顶结束时间
                Date newTopEndTime = calendar.getTime();
                //设置结束时间
                addGroup.setTopEndTime(newTopEndTime);
                //设置置顶时间
                addGroup.setTopTime(new Date());
                //执行修改
                addGroupService.updateById(addGroup);
            }
            //返回结果
            return AjaxResult.success("置顶成功");
        }else{
            //返回结果
            return AjaxResult.success("数据异常,请联系客服。");
        }
    }

    //下架名片
    @PostMapping("/delete/AddWechat/XJ")
    public AjaxResult deleteAddWechat(@RequestBody AddWechat addWechat){
        //查询所有该项目未审核通过的提交全部通过
        List<AuditRecords> auditRecordsList = auditRecordsService.list(new LambdaQueryWrapper<AuditRecords>()
                //任务id
                .eq(AuditRecords::getAddWechatId, addWechat.getId())
                //审核状态
                .eq(AuditRecords::getAddStatus, AuditRecordsEnum.DaiShenHe.getStatus())
                //逻辑删除
                .eq(AuditRecords::getDeleteFlag, Boolean.FALSE)
        );
        //遍历下架名片的所有提交
        auditRecordsList.stream().forEach(ele->{
            //设置状态为审核通过
            ele.setAddStatus(AuditRecordsEnum.ShenHeTongGuo.getStatus());
            //设置默认值
            ele.setUpdateBy(SecurityUtils.getUsername());
            ele.setUpdateTime(new Date());
            //执行修改
            auditRecordsService.updateById(ele);
            //创建订单
            OrderInfo orderInfo = new OrderInfo();
            //设置订单号
            orderInfo.setOrderNo("用户添加微信好友收益-无订单号");
            //设置实际操作金额
            orderInfo.setFund(BigDecimal.valueOf(0.5));
            //设置用户编号
            orderInfo.setUserId(ele.getUserId());
            //设置订单状态
            orderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
            //订单备注
            orderInfo.setDescription("添加好友收益");
            //设置默认值
            orderInfo.setCreateBy(SecurityUtils.getUsername());
            orderInfo.setUpdateBy(SecurityUtils.getUsername());
            orderInfo.setCreateTime(new Date());
            orderInfo.setUpdateTime(new Date());
            orderInfo.setDeleteFlag(Boolean.FALSE);
            //执行添加
            orderInfoMapper.insert(orderInfo);
            //查询完成任务用户编号
            SysUser sysUser = sysUserMapper.selectUserById(ele.getUserId());
            //设置平台收益
            sysUser.setIncome(sysUser.getIncome().add(BigDecimal.valueOf(0.5)));
            //设置默认值
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateBy("平台好友任务完成收益");
            //执行添加
            sysUserMapper.updateUser(sysUser);
            //查询是否有上下级
            List<Invite> list = inviteService.list(new LambdaQueryWrapper<Invite>()
                    //完成任务的用户编号
                    .eq(Invite::getInviteUserId, ele.getUserId())
            );
            //遍历集合
            for (Invite invite : list) {
                if (Objects.nonNull(invite)){
                    //判断是否为 直推
                    if (invite.getInviteType() == InviteEnum.ZhiTui.getType()) {
                        System.out.println("进入了直推");
                        //查询直推用户
                        SysUser ztUser = sysUserMapper.selectUserById(invite.getUserId());
                        //判断直推用户不为 null
                        if (Objects.nonNull(ztUser) && Objects.nonNull(ztUser.getMemberEndTime()) && ztUser.getMemberEndTime().after(new Date())){
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(高级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.5));
                            //设置用户编号
                            ztOrderInfo.setUserId(ztUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            ztUser.setIncome(ztUser.getIncome().add(BigDecimal.valueOf(0.5)));
                            //设置用户团队收益
                            ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(BigDecimal.valueOf(0.5)));
                            //设置默认值
                            ztUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            ztUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(ztUser);

                        } else if (Objects.nonNull(ztUser)) {
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(初级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.3));
                            //设置用户编号
                            ztOrderInfo.setUserId(ztUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            ztUser.setIncome(ztUser.getIncome().add(BigDecimal.valueOf(0.3)));
                            //设置用户团队收益
                            ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(BigDecimal.valueOf(0.3)));
                            //设置默认值
                            ztUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            ztUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(ztUser);
                        }
                    }
                    //判断是否为 间推
                    if (invite.getInviteType() == InviteEnum.JianTui.getType()) {
                        System.out.println("进入了间推");
                        //查询间推用户
                        SysUser jtUser = sysUserMapper.selectUserById(invite.getUserId());
                        //判断直推用户不为 null
                        if (Objects.nonNull(jtUser) && Objects.nonNull(jtUser.getMemberEndTime()) && jtUser.getMemberEndTime().after(new Date())){
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(高级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.2));
                            //设置用户编号
                            ztOrderInfo.setUserId(jtUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            //逻辑删除
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            jtUser.setIncome(jtUser.getIncome().add(BigDecimal.valueOf(0.2)));
                            //设置用户团队收益
                            jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(BigDecimal.valueOf(0.2)));
                            //设置默认值
                            jtUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            jtUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(jtUser);
                        } else if (Objects.nonNull(jtUser)) {
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(初级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.1));
                            //设置用户编号
                            ztOrderInfo.setUserId(jtUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            //逻辑删除
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            jtUser.setIncome(jtUser.getIncome().add(BigDecimal.valueOf(0.1)));
                            //设置用户团队收益
                            jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(BigDecimal.valueOf(0.1)));
                            //设置默认值
                            jtUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            jtUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(jtUser);
                        }
                    }

                }//判断遍历对象不为 null

            }//for each结束

        });//for each结束

        //查询冻结
        Freeze freeze = freezeService.getOne(new LambdaQueryWrapper<Freeze>()
                //用户id
                .eq(Freeze::getUserId, SecurityUtils.getUserId())
                //设置任务
                .eq(Freeze::getAddId, addWechat.getId())
                //逻辑删除
                .eq(Freeze::getDeleteFlag, Boolean.FALSE)
        );
        //查询当前用户
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //判断用户不为 null
        if (Objects.nonNull(sysUser)){
            //设置余额
            sysUser.setScore(sysUser.getScore().add(freeze.getFreezeFund()));
            //设置默认值
            sysUser.setUpdateBy(SecurityUtils.getUsername());
            sysUser.setUpdateTime(new Date());
            //执行修改
            sysUserMapper.updateUser(sysUser);
            //创建订单对象
            OrderInfo orderInfo = new OrderInfo();
            //设置订单号
            orderInfo.setOrderNo("用户发布好友任务冻结资金返还-无订单。");
            //设置金额
            orderInfo.setFund(freeze.getFreezeFund());
            //设置用户编号
            orderInfo.setUserId(SecurityUtils.getUserId());
            //设置订单备注
            orderInfo.setDescription("用户发布好友任务冻结资金返还");
            //设置订单状态
            orderInfo.setOrderType(OrderInfoEnum.HaoYouFaBuDongJieFanHuan.getType());
            //设置默认值
            orderInfo.setCreateTime(new Date());
            orderInfo.setCreateBy(SecurityUtils.getUsername());
            orderInfo.setUpdateTime(new Date());
            orderInfo.setUpdateBy(SecurityUtils.getUsername());
            orderInfo.setDeleteFlag(Boolean.FALSE);
            //执行添加
            orderInfoMapper.insert(orderInfo);
        }
        //调用Service层删除
        addWechatService.update(null,new UpdateWrapper<AddWechat>().lambda()
                //主键id
                .eq(AddWechat::getId,addWechat.getId())
                //设置逻辑删除为 真
                .set(AddWechat::getDeleteFlag,Boolean.TRUE)
        );
        //删除freeze
        freezeService.update(null,new UpdateWrapper<Freeze>().lambda()
                //用户id
                .eq(Freeze::getUserId, SecurityUtils.getUserId())
                //设置任务
                .eq(Freeze::getAddId, addWechat.getId())
                //逻辑删除
                .set(Freeze::getDeleteFlag, Boolean.TRUE)
        );
        //返回结果
        return AjaxResult.success("删除成功,剩余资金已全部返还账户。");
    }


    //获取token
    public static String getAccessToken() throws Exception {
        String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbd664677f8367061&secret=b498ec52efbacda9913b7e717371a7fc";
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // 打印返回的完整响应
//        System.out.println("Response: " + response.toString());
        // 解析 JSON，提取 access_token
        JSONObject jsonResponse = new JSONObject(response.toString());
        String accessToken = jsonResponse.getString("access_token");
        // 返回 access_token
        return accessToken;
    }



    //文字判断
    private static String sendMsgSecurityCheckRequest(String accessToken, String content) {
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头（如果需要的话，这里可以添加更多的请求头）
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

        System.out.println(content);
        // 创建请求体
        String jsonRequest = "{\"content\":\"" + content + "\"}";
        StringEntity entity = new StringEntity(jsonRequest, "UTF-8");
        httpPost.setEntity(entity);

        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(responseBody + "我的拦截结果");
            return responseBody;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //会员直推记录表
    @Resource
    private VipReleaseUserIdMapper vipReleaseUserIdMapper;
    //邀请表(直推间推表)
    @Resource
    private InviteMapper inviteMapper;

    //发布好友
    @PostMapping("/add/wechat")
    public AjaxResult addWechat(@RequestBody AddWechat addWechat) throws Exception {
        if (StringUtils.isBlank(addWechat.getIntro())){
            //返回提示
            return AjaxResult.error("请输入个人简介");
        }
        if (StringUtils.isBlank(addWechat.getQrCode())){
            //返回提示
            return AjaxResult.error("请输入二维码");
        }
        if (Objects.isNull(addWechat.getNeedCount()) || addWechat.getNeedCount() <= 0){
            //返回提示
            return AjaxResult.error("需求人脉数需要大于0");
        }
        //判断是否为暗号审核
        if (addWechat.getExamineType() == AddWechatEnum.AnHao.getStatus()){
            return AjaxResult.error("暗号审核功能待开放");

//            if (StringUtils.isBlank(addWechat.getSecretSignal())){
//                return AjaxResult.error("您当前选择的是暗号审核,请输入暗号后在进行提交。");
//            }
        }
        /********************微信审核****************************************/
        String accessToken = getAccessToken(); // 替换为你的 access_token
        //获取响应
        String responseStr = sendMsgSecurityCheckRequest(accessToken, addWechat.getIntro());
        //解析数据
        JsonObject jsonResponse = JsonParser.parseString(responseStr).getAsJsonObject();
        //获取响应码
        int errcode = jsonResponse.get("errcode").getAsInt();
        //判断响应码
        if (errcode == 87014){
            //返回结果
            return AjaxResult.error("发布的内容不合法。");
        }

        /*******************微信审核******************************************/

        System.out.println(addWechat);
        //查询登录用户
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //得到结果
        BigDecimal needFunds = BigDecimal.valueOf(addWechat.getNeedCount() * 1.5);
        //相减判断用户是否余额足够
        BigDecimal subtract = sysUser.getScore().subtract(needFunds);
        //打印需要金额查看
        System.out.println(needFunds + "==================" + subtract);
        //判断是否足够
        if (subtract.compareTo(BigDecimal.ZERO) < 0){
            return AjaxResult.success("用户余额不足,请充值积分。");
        }
        //设置用户余额
        sysUser.setScore(subtract);
        //设置默认值
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        sysUser.setUpdateTime(new Date());
        //执行修改 此操作扣费
        sysUserMapper.updateUser(sysUser);
        System.out.println(222222);
        System.out.println(SecurityUtils.getUsername());
        System.out.println(SecurityUtils.getLoginUser().getUser().getAvatar());
        SysUser activedUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //设置微信昵称
        addWechat.setWechatName(activedUser.getNickName());
        //设置微信头像
        addWechat.setWechatImg(activedUser.getAvatar());
        //设置影响力
        addWechat.setInfluence(0);
        //设置用户编号
        addWechat.setUserId(SecurityUtils.getUserId());
        //设置状态
        addWechat.setStatus(AddWechatEnum.ShenHeTongGuo.getStatus());
        //设置默认值
        addWechat.setCreateBy(SecurityUtils.getUsername());
        addWechat.setCreateTime(new Date());
        addWechat.setUpdateBy(SecurityUtils.getUsername());
        addWechat.setUpdateTime(new Date());
        addWechat.setDeleteFlag(Boolean.FALSE);
        //执行添加
        addWechatService.save(addWechat);
        //添加冻结表
        Freeze freeze = new Freeze();
        //设置冻结资金
        freeze.setFreezeFund(needFunds);
        //设置冻结的用户编号
        freeze.setUserId(SecurityUtils.getUserId());
        //设置任务id
        freeze.setAddId(addWechat.getId());
        //冻结原因
        freeze.setFreezeReason("用户发布了好友添加任务。");
        //设置默认值
        freeze.setCreateBy(SecurityUtils.getUsername());
        freeze.setCreateTime(new Date());
        freeze.setUpdateBy(SecurityUtils.getUsername());
        freeze.setUpdateTime(new Date());
        freeze.setDeleteFlag(Boolean.FALSE);
        //执行添加
        freezeService.save(freeze);
        //创建订单对象
        OrderInfo orderInfo = new OrderInfo();
        //设置订单号
        orderInfo.setOrderNo("用户发布好友任务冻结资金-无订单号");
        //设置金额
        orderInfo.setFund(needFunds.negate());
        //设置用户编号
        orderInfo.setUserId(SecurityUtils.getUserId());
        //设置订单备注
        orderInfo.setDescription("发布好友任务扣费");
        //设置订单状态
        orderInfo.setOrderType(OrderInfoEnum.HaoYouFaBuDongJie.getType());
        //设置默认值
        orderInfo.setCreateTime(new Date());
        orderInfo.setCreateBy(SecurityUtils.getUsername());
        orderInfo.setUpdateTime(new Date());
        orderInfo.setUpdateBy(SecurityUtils.getUsername());
        orderInfo.setDeleteFlag(Boolean.FALSE);
        //执行添加
        orderInfoMapper.insert(orderInfo);

//        添加直推3人，自动升级会员的功能
        //1、根据发布人的id，查询会员自动升级发布表(vip_release_user_id)是否有此id的记录。
        VipReleaseUserId vipReleaseUserId2 = vipReleaseUserIdMapper.selectOne(new LambdaQueryWrapper<VipReleaseUserId>()
                .eq(VipReleaseUserId::getUserId, SecurityUtils.getUserId())
        );
        if(Objects.nonNull(vipReleaseUserId2)){
            return AjaxResult.success();
        }
        //表里面这个userId没有进行下一步。
        //2、将vip_release_user_id表添加一条数据
        VipReleaseUserId vipReleaseUserId = new VipReleaseUserId();
        vipReleaseUserId.setCreateBy(SecurityUtils.getUsername());
        vipReleaseUserId.setCreateTime(new Date());
        vipReleaseUserId.setUpdateBy(SecurityUtils.getUsername());
        vipReleaseUserId.setUpdateTime(new Date());
        //设置userId
        vipReleaseUserId.setUserId(SecurityUtils.getUserId());
        vipReleaseUserIdMapper.insert(vipReleaseUserId);
        //3、根据发布人的id，查询邀请表查询出邀请人(上级)id
        Invite invite = inviteMapper.selectOne(new LambdaQueryWrapper<Invite>()
                .eq(Invite::getInviteUserId, SecurityUtils.getUserId())
                .eq(Invite::getInviteType, InviteEnum.ZhiTui.getType())
        );
        if(!Objects.nonNull(invite)){
            return AjaxResult.success();
        }
        //4、根据邀请人id，查询(用户表)sys_user出是否是普通会员。是进行下一步
        Long userId = invite.getUserId();

        SysUser sysUser1 = sysUserMapper.selectUserById(userId);
        if(!Objects.nonNull(sysUser1)){
            return AjaxResult.success();
        }

        //5、将sys_user表里面的vip_count字段加一
        //会员不等于空，会员结束时间大于当前时间
        if(!(sysUser1.getMemberId()!=null && sysUser1.getMemberEndTime().after(new Date()))){
            //不是高级会员
            if(sysUser1.getVipCount()!=null){

            sysUser1.setVipCount(sysUser1.getVipCount()+1);
            }else{
                sysUser1.setVipCount(1L);
            }

            sysUserMapper.updateUser(sysUser1);
        }

        //返回结果
        return AjaxResult.success();
    }



    //审核暗号
    @PostMapping("/password/verification")
    public AjaxResult passwordVerification(String verification,Long addId){
        //查询任务
        AddWechat addWechat = addWechatService.getOne(new LambdaQueryWrapper<AddWechat>()
                //任务编号
                .eq(AddWechat::getId, addId)
                //任务暗号
                .eq(AddWechat::getSecretSignal, verification)
                //为暗号审核
                .eq(AddWechat::getExamineType,AddWechatEnum.AnHao.getStatus())
                //需求人数需要大于1
                .gt(AddWechat::getNeedCount,0)
                //逻辑删除
                .eq(AddWechat::getDeleteFlag, Boolean.FALSE)
        );
        if (Objects.isNull(addWechat)){
            //弹出提示
            return AjaxResult.error("暗号错误或任务已不存在。");
        }
        //查询是否为只允许完成一次任务的人
        SysUser addUser = sysUserMapper.selectUserById(addWechat.getUserId());
        //判断接收任务的人是不是发布者本人
        if (addUser.getUserId() == SecurityUtils.getUserId()){
            //返回提示
            return AjaxResult.error("您是任务发布人,审核提交失败。");
        }
        //判断用户是否为只允许薅羊毛一次
        if (addUser.getPickType() == 1){
            //查询是否已经接收过该任务
            AuditRecords bo = auditRecordsService.getOne(new LambdaQueryWrapper<AuditRecords>()
                    //发布用户id
                    .eq(AuditRecords::getAddWechatUserId, addUser.getUserId())
                    //接收任务用户id
                    .eq(AuditRecords::getUserId, SecurityUtils.getUserId())
                    //逻辑删除
                    .eq(AuditRecords::getDeleteFlag, Boolean.FALSE)
                    //查询一条即可
                    .last("limit 1")
            );
            //判断是否存在bo
            if (Objects.nonNull(bo)){
                //返回结果
                return AjaxResult.error("您已完成过该用户发布的任务,无法再次完成。");
            }
        }
        //查询是否已经获取过该任务的奖励
        AuditRecords actived = auditRecordsService.getOne(new LambdaQueryWrapper<AuditRecords>()
                //用户id
                .eq(AuditRecords::getUserId, SecurityUtils.getUserId())
                //任务id
                .eq(AuditRecords::getAddWechatId, addId)
                //逻辑删除
                .eq(AuditRecords::getDeleteFlag, Boolean.FALSE)
                //查询一条
                .last("limit 1")
        );
        //判断是否有查询到审核信息
        if (Objects.nonNull(actived)){
            //返回结果
            return AjaxResult.error("您已使用暗号完成该任务的审核,无法提交,请勿重复提交。");
        }
        //判断任务不为 null
        if (addWechat.getExamineType() == AddWechatEnum.AnHao.getStatus()){
                //创建审核对象
                AuditRecords auditRecords = new AuditRecords();
                //设置用户id
                auditRecords.setUserId(SecurityUtils.getUserId());
                //设置审核项目id
                auditRecords.setAddWechatId(addId);
                //设置审核类型
                auditRecords.setAuditType(AddWechatEnum.AnHao.getStatus());
                //设置状态为审核通过
                auditRecords.setAddStatus(AuditRecordsEnum.ShenHeTongGuo.getStatus());
                //设置审核详情
                auditRecords.setAuditDetails("暗号审核通过,系统已完成验证。");
                //设置默认值
                auditRecords.setCreateBy(SecurityUtils.getUsername());
                auditRecords.setCreateTime(new Date());
                auditRecords.setUpdateBy(SecurityUtils.getUsername());
                auditRecords.setUpdateTime(new Date());
                //设置发布任务的人编号
                auditRecords.setAddWechatUserId(addWechat.getUserId());
                //设置逻辑删除
                auditRecords.setDeleteFlag(Boolean.FALSE);
                //执行添加
                auditRecordsService.save(auditRecords);
                //创建订单
                OrderInfo orderInfo = new OrderInfo();
                //设置订单号
                orderInfo.setOrderNo("用户添加微信好友收益-无订单号");
                //设置实际操作金额
                orderInfo.setFund(BigDecimal.valueOf(0.5));
                //设置用户编号
                orderInfo.setUserId(auditRecords.getUserId());
                //设置订单状态
                orderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                //订单备注
                orderInfo.setDescription("添加好友收益");
                //设置默认值
                orderInfo.setCreateBy(SecurityUtils.getUsername());
                orderInfo.setUpdateBy(SecurityUtils.getUsername());
                orderInfo.setCreateTime(new Date());
                orderInfo.setUpdateTime(new Date());
                orderInfo.setDeleteFlag(Boolean.FALSE);
                //执行添加
                orderInfoMapper.insert(orderInfo);
                //查询完成任务用户编号
                SysUser sysUser = sysUserMapper.selectUserById(auditRecords.getUserId());
                //设置平台收益
                sysUser.setIncome(sysUser.getIncome().add(BigDecimal.valueOf(0.5)));
                //设置默认值
                sysUser.setUpdateTime(new Date());
                sysUser.setUpdateBy("平台好友任务完成收益");
                //执行添加
                sysUserMapper.updateUser(sysUser);
                //给冻结表扣金额
                freezeService.update(null,new UpdateWrapper<Freeze>().lambda()
                        //发布用户id
                        .eq(Freeze::getUserId,addWechat.getUserId())
                        //发布任务编号
                        .eq(Freeze::getAddId,addWechat.getId())
                        //逻辑删除
                        .eq(Freeze::getDeleteFlag,Boolean.FALSE)
                        // 设置金额减少1.5
                        .setSql("freeze_fund = freeze_fund - 1.5")
                );
                //对需求人数 -1
                addWechat.setNeedCount(addWechat.getNeedCount() - 1);
                //设置默认值
                addWechat.setUpdateBy(SecurityUtils.getUsername());
                addWechat.setUpdateTime(new Date());
                //执行修改
                addWechatService.updateById(addWechat);
                //查询是否有上下级
                List<Invite> list = inviteService.list(new LambdaQueryWrapper<Invite>()
                        //完成任务的用户编号
                        .eq(Invite::getInviteUserId, auditRecords.getUserId())
                );
                //遍历集合
                for (Invite invite : list) {
                    if (Objects.nonNull(invite)){
                        //判断是否为 直推
                        if (invite.getInviteType() == InviteEnum.ZhiTui.getType()) {
                            System.out.println("进入了直推");
                            //查询直推用户
                            SysUser ztUser = sysUserMapper.selectUserById(invite.getUserId());
                            //判断直推用户不为 null
                            if (Objects.nonNull(ztUser) && Objects.nonNull(ztUser.getMemberEndTime()) && ztUser.getMemberEndTime().after(new Date())){
                                //创建订单
                                OrderInfo ztOrderInfo = new OrderInfo();
                                //设置订单号
                                ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(高级会员)-无订单号");
                                //设置实际操作金额
                                ztOrderInfo.setFund(BigDecimal.valueOf(0.5));
                                //设置用户编号
                                ztOrderInfo.setUserId(ztUser.getUserId());
                                //设置订单状态
                                ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                                //设置备注
                                ztOrderInfo.setDescription("邀请用户任务完成收益");
                                //设置默认值
                                ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setCreateTime(new Date());
                                ztOrderInfo.setUpdateTime(new Date());
                                ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                                //执行添加
                                orderInfoMapper.insert(ztOrderInfo);
                                //设置用户余额
                                ztUser.setIncome(ztUser.getIncome().add(BigDecimal.valueOf(0.5)));
                                //设置用户团队收益
                                ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(BigDecimal.valueOf(0.5)));
                                //设置默认值
                                ztUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                                ztUser.setUpdateTime(new Date());
                                //执行修改
                                sysUserMapper.updateUser(ztUser);

                            } else if (Objects.nonNull(ztUser)) {
                                //创建订单
                                OrderInfo ztOrderInfo = new OrderInfo();
                                //设置订单号
                                ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(初级会员)-无订单号");
                                //设置实际操作金额
                                ztOrderInfo.setFund(BigDecimal.valueOf(0.3));
                                //设置用户编号
                                ztOrderInfo.setUserId(ztUser.getUserId());
                                //设置订单状态
                                ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                                //设置备注
                                ztOrderInfo.setDescription("邀请用户任务完成收益");
                                //设置默认值
                                ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setCreateTime(new Date());
                                ztOrderInfo.setUpdateTime(new Date());
                                ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                                //执行添加
                                orderInfoMapper.insert(ztOrderInfo);
                                //设置用户余额
                                ztUser.setIncome(ztUser.getIncome().add(BigDecimal.valueOf(0.3)));
                                //设置用户团队收益
                                ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(BigDecimal.valueOf(0.3)));
                                //设置默认值
                                ztUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                                ztUser.setUpdateTime(new Date());
                                //执行修改
                                sysUserMapper.updateUser(ztUser);
                            }
                        }
                        //判断是否为 间推
                        if (invite.getInviteType() == InviteEnum.JianTui.getType()) {
                            System.out.println("进入了间推");
                            //查询间推用户
                            SysUser jtUser = sysUserMapper.selectUserById(invite.getUserId());
                            //判断直推用户不为 null
                            if (Objects.nonNull(jtUser) && Objects.nonNull(jtUser.getMemberEndTime()) && jtUser.getMemberEndTime().after(new Date())){
                                //创建订单
                                OrderInfo ztOrderInfo = new OrderInfo();
                                //设置订单号
                                ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(高级会员)-无订单号");
                                //设置实际操作金额
                                ztOrderInfo.setFund(BigDecimal.valueOf(0.2));
                                //设置用户编号
                                ztOrderInfo.setUserId(jtUser.getUserId());
                                //设置订单状态
                                ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                                //设置备注
                                ztOrderInfo.setDescription("邀请用户任务完成收益");
                                //设置默认值
                                ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setCreateTime(new Date());
                                ztOrderInfo.setUpdateTime(new Date());
                                //逻辑删除
                                ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                                //执行添加
                                orderInfoMapper.insert(ztOrderInfo);
                                //设置用户余额
                                jtUser.setIncome(jtUser.getIncome().add(BigDecimal.valueOf(0.2)));
                                //设置用户团队收益
                                jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(BigDecimal.valueOf(0.2)));
                                //设置默认值
                                jtUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                                jtUser.setUpdateTime(new Date());
                                //执行修改
                                sysUserMapper.updateUser(jtUser);
                            } else if (Objects.nonNull(jtUser)) {
                                //创建订单
                                OrderInfo ztOrderInfo = new OrderInfo();
                                //设置订单号
                                ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(初级会员)-无订单号");
                                //设置实际操作金额
                                ztOrderInfo.setFund(BigDecimal.valueOf(0.1));
                                //设置用户编号
                                ztOrderInfo.setUserId(jtUser.getUserId());
                                //设置订单状态
                                ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                                //设置备注
                                ztOrderInfo.setDescription("邀请用户任务完成收益");
                                //设置默认值
                                ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                                ztOrderInfo.setCreateTime(new Date());
                                ztOrderInfo.setUpdateTime(new Date());
                                //逻辑删除
                                ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                                //执行添加
                                orderInfoMapper.insert(ztOrderInfo);
                                //设置用户余额
                                jtUser.setIncome(jtUser.getIncome().add(BigDecimal.valueOf(0.1)));
                                //设置用户团队收益
                                jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(BigDecimal.valueOf(0.1)));
                                //设置默认值
                                jtUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                                jtUser.setUpdateTime(new Date());
                                //执行修改
                                sysUserMapper.updateUser(jtUser);
                            }
                        }

                    }//判断遍历对象不为 null

                }//for each结束
                //返回结果
                return AjaxResult.success("审核成功,款项已成功打款至客户账户");
            }else{
                //返回不是暗号审核
                return AjaxResult.success("当前任务为人工审核,无法进行暗号验证。");
            }
    }



    //审核不通过
    @PostMapping("/audit/review/failed/{id}")
    public AjaxResult reviewFailed(@PathVariable(value = "id")Long id){
        //查询任务编号
        AuditRecords auditRecords = auditRecordsService.getOne(new LambdaQueryWrapper<AuditRecords>()
                //编号
                .eq(AuditRecords::getId,id)
                //任务状态
                .eq(AuditRecords::getAddStatus,AuditRecordsEnum.DaiShenHe.getStatus())
                //逻辑删除
                .eq(AuditRecords::getDeleteFlag,Boolean.FALSE)
        );
        //判断任务不为 null
        if (Objects.isNull(auditRecords)){
            //返回结果
            return AjaxResult.error("任务已审核或不存在~");
        }
        //查询任务发布人
        AddWechat addWechat = addWechatService.getOne(new LambdaQueryWrapper<AddWechat>()
//                //需求人数需要大于0
//                .gt(AddWechat::getNeedCount,0)
                //为人工审核
                .eq(AddWechat::getExamineType,AddWechatEnum.RenGong.getStatus())
                //任务id
                .eq(AddWechat::getId,auditRecords.getAddWechatId())
        );
        //判断任务是否还存在
        if (addWechat.getDeleteFlag() == Boolean.FALSE){
            //设置任务为不通过
            auditRecordsService.update(null,new UpdateWrapper<AuditRecords>().lambda()
                    //编号
                    .eq(AuditRecords::getId,id)
                    //逻辑删除
                    .eq(AuditRecords::getDeleteFlag,Boolean.FALSE)
                    //任务状态
                    .set(AuditRecords::getAddStatus,AuditRecordsEnum.ShenHeBuTongGuo.getStatus())
                    //设置默认值
                    .set(AuditRecords::getUpdateBy,SecurityUtils.getUsername())
                    //设置默认时间
                    .set(AuditRecords::getUpdateTime,new Date())
            );
            //将任务需求人数 +1
            addWechatService.update(null,new UpdateWrapper<AddWechat>().lambda()
                    //任务编号
                    .eq(AddWechat::getId,addWechat.getId())
                    //设置需求人数 + 1
                    .setSql("need_count = need_count + 1")
            );
            //冻结表
            freezeService.update(null,new UpdateWrapper<Freeze>().lambda()
                    //任务编号
                    .eq(Freeze::getAddId,addWechat.getId())
                    //设置金额 + 1.5
                    .setSql("freeze_fund = freeze_fund +1.5")
            );
            /**
             * 冻结 150块钱 需求100人数
             * 需求人数 -1
             * 审核通过 -1.5元
             * 审核不通过 +1需求人数
             */
            //返回结果
            return AjaxResult.success("审核不通过。");
        }else{
            //返回结果
            return AjaxResult.success("当前审核的任务似乎已下架了。");
        }
    }


    //审核人工
    @PostMapping("/audit/pass/{id}")
    public AjaxResult AuditPass(@PathVariable(value = "id")Long id){
        //查询任务编号
        AuditRecords auditRecords = auditRecordsService.getOne(new LambdaQueryWrapper<AuditRecords>()
                //编号
                .eq(AuditRecords::getId,id)
                //任务状态
                .eq(AuditRecords::getAddStatus,AuditRecordsEnum.DaiShenHe.getStatus())
                //逻辑删除
                .eq(AuditRecords::getDeleteFlag,Boolean.FALSE)
        );
        //判断任务不为 null
        if (Objects.isNull(auditRecords)){
            //返回结果
            return AjaxResult.error("任务已审核或不存在~");
        }
        //查询任务发布人
        AddWechat addWechat = addWechatService.getOne(new LambdaQueryWrapper<AddWechat>()
                //需求人数需要大于0
//                .gt(AddWechat::getNeedCount,0)
                //为人工审核
                .eq(AddWechat::getExamineType,AddWechatEnum.RenGong.getStatus())
                //任务id
                .eq(AddWechat::getId,auditRecords.getAddWechatId())
        );
        //判断任务是否还存在
        if (addWechat.getDeleteFlag() == Boolean.FALSE){
            //设置状态为审核通过
            auditRecords.setAddStatus(AuditRecordsEnum.ShenHeTongGuo.getStatus());
            //设置默认值
            auditRecords.setUpdateBy(SecurityUtils.getUsername());
            auditRecords.setUpdateTime(new Date());
            //执行修改
            auditRecordsService.updateById(auditRecords);
            //创建订单
            OrderInfo orderInfo = new OrderInfo();
            //设置订单号
            orderInfo.setOrderNo("用户添加微信好友收益-无订单号");
            //设置实际操作金额
            orderInfo.setFund(BigDecimal.valueOf(0.5));
            //设置用户编号
            orderInfo.setUserId(auditRecords.getUserId());
            //设置订单状态
            orderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
            //订单备注
            orderInfo.setDescription("添加好友收益");
            //设置默认值
            orderInfo.setCreateBy(SecurityUtils.getUsername());
            orderInfo.setUpdateBy(SecurityUtils.getUsername());
            orderInfo.setCreateTime(new Date());
            orderInfo.setUpdateTime(new Date());
            orderInfo.setDeleteFlag(Boolean.FALSE);
            //执行添加
            orderInfoMapper.insert(orderInfo);
            //查询完成任务用户编号
            SysUser sysUser = sysUserMapper.selectUserById(auditRecords.getUserId());
            //设置平台收益
            sysUser.setIncome(sysUser.getIncome().add(BigDecimal.valueOf(0.5)));
            //设置默认值
            sysUser.setUpdateTime(new Date());
            sysUser.setUpdateBy("平台好友任务完成收益");
            //执行添加
            sysUserMapper.updateUser(sysUser);
//            //给冻结表扣金额
//            freezeService.update(null,new UpdateWrapper<Freeze>().lambda()
//                    //发布用户id
//                    .eq(Freeze::getUserId,addWechat.getUserId())
//                    //发布任务编号
//                    .eq(Freeze::getAddId,addWechat.getId())
//                    //逻辑删除
//                    .eq(Freeze::getDeleteFlag,Boolean.FALSE)
//                    // 设置金额减少1.5
//                    .setSql("freeze_fund = freeze_fund - 1.5")
//            );
//            //对需求人数 -1
//            addWechat.setNeedCount(addWechat.getNeedCount() - 1);
//            //设置默认值
//            addWechat.setUpdateBy(SecurityUtils.getUsername());
//            addWechat.setUpdateTime(new Date());
//            //执行修改
//            addWechatService.updateById(addWechat);
            //查询是否有上下级
            List<Invite> list = inviteService.list(new LambdaQueryWrapper<Invite>()
                    //完成任务的用户编号
                    .eq(Invite::getInviteUserId, auditRecords.getUserId())
            );
            //遍历集合
            for (Invite invite : list) {
                if (Objects.nonNull(invite)){
                    //判断是否为 直推
                    if (invite.getInviteType() == InviteEnum.ZhiTui.getType()) {
                        System.out.println("进入了直推");
                        //查询直推用户
                        SysUser ztUser = sysUserMapper.selectUserById(invite.getUserId());
                        //判断直推用户不为 null
                        if (Objects.nonNull(ztUser) && Objects.nonNull(ztUser.getMemberEndTime()) && ztUser.getMemberEndTime().after(new Date())){
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(高级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.5));
                            //设置用户编号
                            ztOrderInfo.setUserId(ztUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            ztUser.setIncome(ztUser.getIncome().add(BigDecimal.valueOf(0.5)));
                            //设置用户团队收益
                            ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(BigDecimal.valueOf(0.5)));
                            //设置默认值
                            ztUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            ztUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(ztUser);

                        } else if (Objects.nonNull(ztUser)) {
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(初级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.3));
                            //设置用户编号
                            ztOrderInfo.setUserId(ztUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            ztUser.setIncome(ztUser.getIncome().add(BigDecimal.valueOf(0.3)));
                            //设置用户团队收益
                            ztUser.setTeamBenefits(ztUser.getTeamBenefits().add(BigDecimal.valueOf(0.3)));
                            //设置默认值
                            ztUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            ztUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(ztUser);
                        }
                    }
                    //判断是否为 间推
                    if (invite.getInviteType() == InviteEnum.JianTui.getType()) {
                        System.out.println("进入了间推");
                        //查询间推用户
                        SysUser jtUser = sysUserMapper.selectUserById(invite.getUserId());
                        //判断直推用户不为 null
                        if (Objects.nonNull(jtUser) && Objects.nonNull(jtUser.getMemberEndTime()) && jtUser.getMemberEndTime().after(new Date())){
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(高级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.2));
                            //设置用户编号
                            ztOrderInfo.setUserId(jtUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            //逻辑删除
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            jtUser.setIncome(jtUser.getIncome().add(BigDecimal.valueOf(0.2)));
                            //设置用户团队收益
                            jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(BigDecimal.valueOf(0.2)));
                            //设置默认值
                            jtUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            jtUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(jtUser);
                        } else if (Objects.nonNull(jtUser)) {
                            //创建订单
                            OrderInfo ztOrderInfo = new OrderInfo();
                            //设置订单号
                            ztOrderInfo.setOrderNo("邀请用户完成添加好友任务收益(初级会员)-无订单号");
                            //设置实际操作金额
                            ztOrderInfo.setFund(BigDecimal.valueOf(0.1));
                            //设置用户编号
                            ztOrderInfo.setUserId(jtUser.getUserId());
                            //设置订单状态
                            ztOrderInfo.setOrderType(OrderInfoEnum.PingTaiRenWuShouYi.getType());
                            //设置备注
                            ztOrderInfo.setDescription("邀请用户任务完成收益");
                            //设置默认值
                            ztOrderInfo.setCreateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setUpdateBy(SecurityUtils.getUsername());
                            ztOrderInfo.setCreateTime(new Date());
                            ztOrderInfo.setUpdateTime(new Date());
                            //逻辑删除
                            ztOrderInfo.setDeleteFlag(Boolean.FALSE);
                            //执行添加
                            orderInfoMapper.insert(ztOrderInfo);
                            //设置用户余额
                            jtUser.setIncome(jtUser.getIncome().add(BigDecimal.valueOf(0.1)));
                            //设置用户团队收益
                            jtUser.setTeamBenefits(jtUser.getTeamBenefits().add(BigDecimal.valueOf(0.1)));
                            //设置默认值
                            jtUser.setUpdateBy("系统-邀请好友完成好友添加收益(高级会员)");
                            jtUser.setUpdateTime(new Date());
                            //执行修改
                            sysUserMapper.updateUser(jtUser);
                        }
                    }

                }//判断遍历对象不为 null

            }//for each结束

            //返回结果
            return AjaxResult.success("审核成功,款项已成功打款至客户账户");
        }else{
            //返回任务已无
            return AjaxResult.error("您提交的任务已结束");
        }
    }

}
